import os
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import api_view

from utils.imageupload import ImageUpload
from NetShop.models import CustomLogin
from PetNetadmin.serializers import CustomLoginMessageSerializer


# 返回顾客个人信息
class GetCustomInfo(APIView):
    def get(self, request):
        id = request.GET.get('id')
        # print(request.GET.get('id'))
        info = CustomLogin.objects.get(id=id)
        serializer = CustomLoginMessageSerializer(instance=info)
        result = {
            'data': serializer.data,
            'code': 2000,
            'msg': '获取成功'
        }
        return Response(result, status=status.HTTP_200_OK)

    # 修改个人信息，需要删除原来的图片
    def post(self, request):
        print(request.data)
        get_message = request.data
        id = request.data['id']
        updateMsg = CustomLogin.objects.get(id=id)
        new_img_url = get_message.get('avatar', None)
        old_img_url = CustomLogin.objects.get(id=id).avatar
        if new_img_url and new_img_url != old_img_url:
            print(old_img_url)
            old_img_url = old_img_url.split(':8000/')[1]
            if os.path.exists(old_img_url):
                os.remove(old_img_url)
                print(f'删除成功{old_img_url}')
        serializer = CustomLoginMessageSerializer(instance=updateMsg, data=get_message, partial=True)
        if serializer.is_valid(raise_exception=True):
            serializer.save()
            result = {
                'data': serializer.data,
                'code': 2000,
                'msg': '添加成功'
            }
        return Response(result, status=status.HTTP_200_OK)
# 上传图片
class UploadCustomAvatarImageView(APIView):
    def post(self, request):
        result = ImageUpload(request, 'avatar')
        print(result)
        if result['code'] == 2000:
            return Response(data=result['img'])
        else:
            return Response('没有上传成功')

# 修改密码
@api_view(['POST'])
def editPassword(request):
    print(request.data)
    id = request.data['id']
    updateMsg = CustomLogin.objects.get(id=id)
    password = request.data['password']
    data = {
        'password': password
    }
    serializer = CustomLoginMessageSerializer(instance=updateMsg,data=data,partial=True)
    if serializer.is_valid(raise_exception=True):
        print(serializer.validated_data)
        serializer.save()
    result = {
        'code': 2000,
        'msg': '添加成功'
    }
    return Response(result, status=status.HTTP_200_OK)
